package com.mbigger.admin.common;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.mbigger.admin.entity.Acl;
import com.mbigger.admin.entity.Role;
import com.mbigger.admin.entity.User;
import com.mbigger.admin.service.AclService;
import com.mbigger.admin.service.RoleService;
import com.mbigger.admin.service.UserService;

public class ShiroRealm extends AuthorizingRealm {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private AclService aclService;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String username = (String) principalCollection.getPrimaryPrincipal();
		int userId = userService.findByKeyword(username).getId();
		Set<String> roles = getRoleSetByUserId(userId);
		Set<String> permissions = getPermissionSetByUserId(userId);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(roles);
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		if (authenticationToken.getPrincipal() == null) {
            return null;
        }
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		String username = token.getUsername();
		if(!StringUtils.isEmpty(username)) {
			User user = userService.findByKeyword(username);
			if(user != null) {
				String password = user.getPassword();
				return new SimpleAuthenticationInfo(username, password, getName());
			}
		}
		return null;
	}
	
	/**
	 * 获取用户角色集合
	 * @param userId
	 * @return
	 */
	private Set<String> getRoleSetByUserId(int userId){
		Set<String> set = new HashSet<>();
		List<Role> list = roleService.getRoleListByUserId(userId);
		list.forEach((r)->{
			set.add(r.getName());
		});
		return set;
	}
	
	/**
	 * 获取用户权限集合
	 * @param userId
	 * @return
	 */
	private Set<String> getPermissionSetByUserId(int userId){
		Set<String> set = new HashSet<>();
		List<Acl> list = aclService.getAclListByUserId(userId);
		list.forEach((r)->{
			set.add(r.getPermission());
		});
		return set;
	}

}
